/**
 * Created by legion on 2018/9/13.
 */
(function($, window) {
    "use strict";
    var list = (function () {
        list = function (options) {
            this.settings = $.extend({}, $.fn.extend);

            //this.element = element;
            this.init();
        };
        list.prototype = {
            /*说明：初始化插件*/
            init: function () {
                let self = this;

                self.selectors = this.settings.selectors;
                self.body = this.selectors.body;
                self.arrival = this.selectors.arrival;
                self.departure = this.selectors.departure;
                self.header = this.selectors.header;
                self.sortEl = this.selectors.recommedSort;
                self.recommedCondition = this.selectors.recommedCondition;
                self.location = this.selectors.location;
                self.recommedContent = this.selectors.recommedContent;
                self.flag = true;

                self._initPage();
                self._dateSelect();
                self._eventBinding();
                self._getDistrict();
                self.getListItem(true, true);

                $('.qt-mask').bind( "touchmove", function (e) {
                    e.preventDefault();
                });
            },
            //页面事件
            _initPage: function () {
                let self = this;

                //头部基本信息赋值
                $(".select-city").text(self.settings.hotelData.city_name);

                $("#search-input").val(self.settings.hotelData.hotel_name);

                $("#city-search").val(self.settings.hotelData.keyword);
                //日期
                var arrivalTime = self.settings.hotelData.arrival_date.split('-');
                $(self.arrival).html(arrivalTime[1] + "-" + arrivalTime[2]);

                var departureTime = self.settings.hotelData.departure_date.split('-');
                $(self.departure).html(departureTime[1] + "-" + departureTime[2]);

                //页面高度处理
                $('.qt-wrapper').css("marginTop", $(self.header).height());

                $('.qt-sub-header').css('top', $(self.header).height() + 20);

                $('.list-inner').css('marginTop', $(self.header).height() + $(".qt-sub-header").height()+20 );

                $('.list-inner').height(api.winHeight - $(self.header).height() + $(".qt-sub-header").height()+20);

                $(self.body).on('click', '.qt-mask', function () {
                    $('.qt-mask').css({'display':'none','opacity':0,'z-index':-1});
                    $(self.recommedContent).animate({
                        height: 0,
                        opacity: 0
                    },150);
                    $(self.recommedCondition).find('li').not('.sort-btn').removeClass('select');
                });
            },
            //日期选择
            _dateSelect: function () {
                let self = this;
                let el = $('.time-condition');
                el.on('click',function () {
                    $('.mask_calendar').show();
                });
                $('.mask_calendar').on('click',function (e) {
                    if(e.target.className === "mask_calendar"){
                        $('.calendar').slideUp(200);
                        $('.mask_calendar').fadeOut(200);
                    }
                });
                el.calendarSwitch({
                    selectors : {
                        sections : ".calendar"
                    },
                    index : 4,      //展示的月份个数
                    animateFunction : "slideToggle",        //动画效果
                    controlDay:true,//知否控制在daysnumber天之内，这个数值的设置前提是总显示天数大于90天
                    daysnumber : "90",     //控制天数
                    comeColor : "#2EB6A8",       //入住颜色
                    outColor : "#2EB6A8",      //离店颜色
                    comeoutColor : "#E0F4F2",        //入住和离店之间的颜色
                    callback :function(startDate, endDate, numDate){//回调函数
                        $('.mask_calendar').fadeOut(200);

                        self.settings.hotelData.arrival_date   = startDate;
                        self.settings.hotelData.departure_date = endDate;
                        self.settings.hotelData.date_amount    = numDate;
                        $api.setStorage('hotel_data', $api.jsonToStr(self.settings.hotelData));
                        self.getListItem(true, true);

                        api.sendEvent({
                            name: 'listFrmTimeEvt'
                        });
                    } ,
                    comfireBtn:'.comfire'//确定按钮的class或者id
                });
            },
            //事件绑定
            _eventBinding: function () {
                let self = this;
                $("body").on("click", ".list-item", function() {
                    let hotel_id = $(this).data("hotelid");
                    //let price = $(this).find('.price').text().match(/\d+(\.\d+)?/)[0];
                    let price = $(this).find('.price').text();
                    if (price === '暂不可预定') return false;
                    self.settings.hotelData.hotel_id = hotel_id;
                    $api.setStorage('hotel_data', JSON.stringify(self.settings.hotelData));
                    setTimeout(function(){
                        api.openWin({
                            name: 'room_frm',
                            url: './room_frm.html',
                            slidBackEnabled:false,
                            pageParam: {
                                hotelId : hotel_id
                            }
                        });
                    },300);
                });
                //关键字搜索
                $("#city-search").blur(function(e) {
                    e.preventDefault();
                    self.settings.hotelData.hotel_name = $.trim($(this).val());
                    $api.setStorage('hotel_data', JSON.stringify(self.settings.hotelData));
                    self.getListItem(true, true);
                });

                $('#backTop').click(function () {
                    $(".list-inner").finish().animate({"scrollTop": -50},500);
                });

                $(".list-inner").scroll(function (ev) {
                    event.preventDefault();
                    var totalheight = parseInt($(".list-inner ul").height()) - parseFloat($(".list-inner").scrollTop());

                    var scrollTop = parseFloat($('.list-inner').scrollTop());
                    if (scrollTop > 300) {
                        $('#backTop').show();
                    } else {
                        $('#backTop').hide();
                    }
                    if (self.flag) {
                        if (totalheight <= 800) {
                            self.flag = false;
                            self.getListItem(false, false);
                        }
                    }
                });

                api.addEventListener({
                    name: 'starPriceEv'
                }, function(ret) {
                    if (ret.value.data.star.length > 0) {
                        self.settings.hotelData.StarRate = ret.value.data.star[0];
                        $('.star-price').html(ret.value.data.star[1] + ', ￥'+ret.value.data.price[0] + ' - ' + '￥' + ret.value.data.price[1]);
                    } else {
                        if (parseInt(ret.value.data.star[0]) === 0 && parseInt(ret.value.data.star[1] === 1000)) {
                            self.settings.hotelData.StarRate = '';
                        }
                    }
                    self.settings.hotelData.LowRate = ret.value.data.price[0];
                    self.settings.hotelData.HighRate = ret.value.data.price[1];
                    self.getListItem(true, true);
                });

                api.addEventListener({
                    name: 'cancelCheckEv'
                }, function (ret) {
                    $(self.recommedCondition).find('li').not('.sort-btn').removeClass('select');
                });

                $(self.recommedCondition).find('li').click(function (ev) {
                    let h = 0,
                        o = 0,
                        t = 0;
                    let maskCss = {};
                    let i = $(this).index();
                    let cls = $(this).data('for');
                    $(self.recommedContent).find('.' + cls).removeClass('qt-hide').siblings().addClass('qt-hide');

                    if (i === 0) {
                        if ($(this).hasClass('active')) {//隐藏
                            $(this).removeClass('active');
                            h = 0;
                            o = 0;
                            t = -999;
                            maskCss = {'display':'none','opacity':0,'z-index':-1};
                        } else {//显示
                            $(this).addClass('active').siblings().removeClass('select');
                            h = 165;
                            o = 1;
                            t = $('.qt-wrapper').offset().top;
                            maskCss = {'display':'block','opacity':0.4,'z-index':1};
                        }
                    } else if(i === 2) {
                        if ($(this).hasClass('select')) {//隐藏
                            $(this).removeClass('select');
                            h = 0;
                            o = 0;
                            t = -999;
                            maskCss = {'display':'none','opacity':0,'z-index':-1};
                        } else {//显示
                            $(this).addClass('select').siblings().removeClass('active');
                            o = 1;
                            h = 464;
                            t = $('.qt-wrapper').offset().top;
                            maskCss = {'display':'block','opacity':0.4,'z-index':1};
                        }
                    } else if (i === 1) {
                        if ($(this).hasClass('select')) {//隐藏
                            $(this).removeClass('select');
                            api.closeFrame({
                                name: 'star_price_frm'
                            });
                        } else {//显示
                            $(this).addClass('select').siblings().removeClass('active');
                            api.openFrame({
                                name: 'star_price_frm',
                                url: './star_price_frm.html',
                                rect: {
                                    x: 0,
                                    y: 0,
                                    w: 'auto',
                                    h: api.winHeight
                                },
                                bgColor: 'rgba(0,0,0,0)'
                            });
                        }
                    }
                    if (i !== 1) {
                        $('.qt-mask').css(maskCss);
                        $(self.recommedContent).animate({
                            height: h,
                            opacity: o,
                            top: t
                        },150);

                    }
                });

                $(self.body).on('click', self.sortEl + " li", function () {
                    let i = $(this).index();
                    console.log(i);
                    if (i === 0) {
                        self.settings.hotelData.sort = 'Default';
                    } else if(i === 1) {
                        self.settings.hotelData.sort = 'RateAsc';
                    } else if(i === 2) {
                        self.settings.hotelData.sort = 'RateDesc';
                    } else if(i === 3) {
                        self.settings.hotelData.sort = 'StarRankDesc';
                    }
                    $('.qt-mask').css({'display':'none','opacity':0,'z-index':-1});
                    $(self.recommedContent).animate({
                        height: 0,
                        opacity: 0
                    },150);
                    $(self.recommedCondition).find('li').eq(1).removeClass('select');
                    $api.setStorage('hotel_data', self.settings.hotelData);
                    self.getListItem(true, true);
                });

                $(self.body).on('click', self.location + " .left-nav li", function () {
                    let _this = $(this);
                    let target = '.' + _this.data('for');
                    let otherTarget = '.' + _this.siblings().data('for');

                    if (!_this.hasClass('active')) _this.toggleClass('active').siblings().removeClass('active');

                    $(target).removeClass('qt-hide').siblings().addClass('qt-hide').find();

                    let selectel = $(otherTarget + ' > ul').find('p.check-out.active');

                    if (selectel.length < 1) {
                        _this.siblings().removeClass('record');
                    } else {
                        _this.siblings().addClass('record');
                    }
                });

                $(self.body).on('click', self.location + " .right-detail li", function (e) {
                    let _this = $(this);
                    let target = '.' + _this.data('path');
                    let codeId = parseInt(_this.data('code'));
                    if (target === '.business') {
                        $(self.location + " .right-detail .administration .all").find('p.check-out').click();//模拟选择不限
                        $(self.location + ' .left-nav').find('.administration-nav').removeClass('record');
                    } else {
                        $(self.location + " .right-detail .business .all").find('p.check-out').click();//模拟选择不限
                        $(self.location + ' .left-nav').find('.business-zone-nav').removeClass('record');
                    }
                    $(target + ' .all p.check-out').removeClass('active');
                    if (_this.find('p.check-out').hasClass('active')) {
                        _this.find('p.check-out').removeClass('active');
                        self.settings.selectedAreaIds.forEach(function (v, i) {
                            if (v === codeId) {
                                self.settings.selectedAreaIds.splice(v,1);
                            }
                        });
                        let activeLen = _this.siblings('li').find('p.check-out.active').length;
                        if (activeLen < 1) {
                            $(self.location + " .right-detail .administration .all").find('p.check-out').click();//模拟选择不限
                        }
                    } else {
                        self.settings.selectedTerm = target;
                        self.settings.selectedAreaIds.push(codeId);
                        _this.find('p.check-out').addClass('active');
                    }
                });

                $(self.body).on('click', self.location + " .right-detail .all," + self.location+' .empty', function () {
                    let _this = $(this);
                    let target = '.' + _this.data('for');
                    if (target === '.all') {
                        $('.business,.administration').find('p.check-out').addClass('active');
                        $('.business,.administration').find('ul li p.check-out').removeClass('active');
                    } else {
                        $(target).find('p.check-out').addClass('active');

                        $(target).find('ul li p.check-out').removeClass('active');
                    }
                    self.settings.selectedAreaIds = [];

                });
                $(self.body).on('click', self.location + ' .submit', function () {

                    if (self.settings.selectedTerm === '.business') {
                        self.settings.hotelData.BusinessZoneId = self.settings.selectedAreaIds.join(',');
                    } else {
                        self.settings.hotelData.DistrictId = self.settings.selectedAreaIds.join(',');
                    }
                    $('.qt-mask').css({'display':'none','opacity':0,'z-index':-1});
                    $(self.recommedContent).animate({
                        height: 0,
                        opacity: 0,
                        top: -999
                    },150);
                    $(self.recommedCondition).find('li').not('.sort-btn').removeClass('select');
                    $api.setStorage('hotel_data', self.settings.hotelData);
                    self.getListItem(true, true);
                });
            },
            //行政区
            _getDistrict: function() {
                let self = this;
                //商业区
                ajax({
                    url: Config.hotel.getDistrict,
                    data: {
                        city_name: self.settings.hotelData.city_name
                    }
                },function(ret){
                    let dataInter = ret.data['CommericalLocations'];//商业圈

                    $(self.location + ' .business').find('ul').html(doT.template($("#businessTpl").text())(dataInter));

                    let dataInter1 = ret.data['Districts'];//行政区
                    $(self.location + ' .administration').find('ul').html(doT.template($("#administrationTpl").text())(dataInter1));
                }, true, false)
            },
            /**
             * @param isFresh
             * @param isMask
             */
            getListItem: function (isFresh, isMask) {
                let self = this;

                let container = $(".list-content .content ul");
                if (isFresh) {
                    container.empty();
                    self.settings.pageIndex = 1;
                } else {
                    if(self.settings.pageIndex < self.settings.maxPage){
                        self.settings.pageIndex++;
                    }
                }
                var param = {};
                param.url = Config.hotel.getHotelList;

                self.settings.hotelData.stay_city = self.settings.hotelData.city_name;
                //页数
                self.settings.hotelData.page_number = self.settings.pageIndex;
                //每页条数
                self.settings.hotelData.limit = 10;
                param.data = self.settings.hotelData;
                if (self.settings.pageIndex >= self.settings.maxPage) {
                    container.append('<div class="qt-mtb10 qt-center">已滚动到底部</div>');
                    return false;
                } else {
                    ajax(param, function(ret) {
                        if (ret.code === 1) {
                            //$toast(self.settings.hotelData.city_name + (ret.count+'家'), 3000, 'b');
                            let dataInter = ret.data;
                            if (dataInter.length === 0) {
                                $toast('暂无内容');
                                return false;
                            }
                            self.settings.maxPage = parseInt(ret.data[0].totalCount/10) + 1;
                            console.log(self.settings.maxPage);
                            let interText = doT.template($("#hotelTel").text());
                            container.append(interText(dataInter));
                            self.flag = true;
                        } else {
                            if(ret.msg === '无符合条件数据'){
                                container.html($('.no-data').removeClass('.qt-hide').html());
                            } else {
                                container.html("<li style='text-align: center;'>" + ret.msg + "</li>");
                            }
                        }
                    }, true, isMask);
                }
                api.refreshHeaderLoadDone();
            }

        };
        return list;
    })();
    $.fn.extend = {
        selectors: {
            body: 'body'
            ,arrival: "#startDate"
            ,departure: "#endDate"
            ,recommedCondition: ".condition-select"//推荐排序头部
            ,header: "#header"
            ,location: ".location-area-filter"//区域筛选
            ,recommedSort: ".recommend-sort"//推荐排序
            ,recommedContent: '.qt-sidebar.top'
        }
        //基本参数
        ,hotelData: JSON.parse($api.getStorage('hotel_data'))
        //最大页数
        ,maxPage: 999
        //当前页数
        ,pageIndex: 1
        //排序方式
        ,currSort: 'Default'
        //行政区 - 商业区 选择id
        ,selectedAreaIds: []
        //选择的条件
        ,selectedTerm: 'administration'

    };
    window.list = list;
})(jQuery, window);